<template>
    <NSpace justify="center">
        <NImage v-if="!modify" width="120" :src="imgurl" fallback-src="/avatar-defalut-small.webp">
        </NImage>
        <input v-if="modify" ref="uploadInput" type="file" id="fileInput" accept="image/*"
            @change="uploadImage"></input>

        <!-- <n-upload v-if="modify" :action="uploadUrl" list-type="image-card" accept="image/*" :directory-dnd="true"
            :headers="headerList" :multiple="false" :max="1" :default-file-list="previewFileList"
            @preview="handlePreview" @before-upload="beforeUpload" /> -->
        <NThing>
            <template #header>
                昵称：{{ login_status.nickname }}
            </template>
            <template #description>
                用户名：{{ login_status.account }}
            </template>
            你所热爱的，便是你的生活。
            <template #action>
                <NButton size="small" @click="handleChange">修改</NButton>
            </template>
        </NThing>
    </NSpace>
    <n-modal v-model:show="showModal" preset="card" style="width: 600px" title="一张很酷的图片">
        <img :src="previewImageUrl" style="width: 100%">
    </n-modal>
</template>
<script setup lang="ts">
import { NSpace, NImage, NThing, NButton, NList, NListItem, NUpload } from "naive-ui";
import type { UploadFileInfo } from 'naive-ui'
import axios from "@/axios"



import { loginStatus } from "@/stores/counter";
import { ref } from "vue";
const login_status = loginStatus();

const modify = ref(false);
const uploadInput = ref();
const info = ref("");
const showModal = ref(false);
const previewImageUrl = ref("");
const previewFileList = ref<UploadFileInfo[]>([
])

const uploadUrl = ref("");

const headerList = ref({
    Authorization: login_status.token
});

const imgurl = window.apiurl +"avatar/"+ login_status.avatarUrl;




const domain = window.location.hostname;
console.log(domain);
uploadUrl.value = (domain == "localhost" ? 'http://localhost:8088/' : 'http://47.94.82.79:8088/') + 'users/upload';

function fileToBase64(file: File): Promise<string | ArrayBuffer | null> {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);        // 读取为 Data URL
        reader.onload = () => resolve(reader.result);      // ""
        reader.onerror = reject;
    });
}
async function uploadImage() {
    const file = uploadInput.value.files[0];
    console.log(file);
    console.log(JSON.stringify(file));
    if (!file) return;

    // 1) 大小校验：0.5 MB = 512 * 1024 B
    const maxSize = 512 * 1024;
    if (file.size > maxSize) {
        window.$utils.message.error("图片不超过1MB");
        uploadInput.value.value = ''; // 清空
        return;
    }

    const base64 = await fileToBase64(file);

    axios.post("/users/upload", { data: JSON.stringify(base64) }, {
    }).then((response) => {
        // 成功请求数据，返回数据
        window.$utils.message.success("上传成功");
    }).catch((err) => {
        // 请求数据失败，返回错误
        window.$utils.message.error("上传失败：" + err);
    })

};


async function beforeUpload(data: {
    file: UploadFileInfo
    fileList: UploadFileInfo[]
}) {
    // 图片不超过1MB
    const isLarge = (data.file.file?.size || 0) < 1024 * 1024;
    if (!isLarge) {
        window.$utils.message.error("图片不超过1MB");
        return false;
    }
    return true;
}


function handleChange() {
    modify.value = !modify.value;
    window.$utils.message.error("功能未实现")
}

function handlePreview(file: UploadFileInfo) {
    const { url } = file
    previewImageUrl.value = url as string
    showModal.value = true
}

</script>